package com.yulang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yulang.entity.SysPermission;
import com.yulang.entity.SysUser;
import com.yulang.entity.SysUserRole;
import com.yulang.mapper.SysPermissionMapper;
import com.yulang.mapper.SysUserMapper;
import com.yulang.mapper.SysUserRoleMapper;
import com.yulang.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public SysUser findByUserName(String username) {
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.lambda()
                .eq(SysUser::getMobile,username)
                .or()
                .eq(SysUser::getUsername,username);
        return getOne(query);
    }

    @Override
    public SysUser findByUsernameContainsPermission(String username) {
        SysUser sysUser = findByUserName(username);
        final List<SysPermission> sysPermissions = sysPermissionMapper.selectByUserId(sysUser.getId() + "");
        sysUser.setPermissions(sysPermissions);
        return sysUser;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdateUser(SysUser sysUser) {
        if(sysUser.getId()==null) {
            sysUser.setPassword(passwordEncoder.encode("abc123456"));
        }
        this.saveOrUpdate(sysUser);
        QueryWrapper<SysUserRole> query = new QueryWrapper<>();
        query.lambda().eq(SysUserRole::getUserId,sysUser.getId());
        sysUserRoleMapper.delete(query);

        for (Long roleId : sysUser.getRoleIds()) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUser.getId()+"");
            sysUserRole.setRoleId(roleId+"");
            sysUserRoleMapper.insert(sysUserRole);
        }
    }


}
